clear all
close all

%  =======================================================================================================================================================
% 
%  Code Description: 
%  This codefile generates figures and tables from the model application in Section 4, including (i) the illustrative 
%  example of the Step 1 losses due to cross-fund holdings within our stresstest model framework as provided in internet appendix B and (ii) 
%  the parameter sensitivity analysis provided in internet appendix C.2. 
% 
%  =======================================================================================================================================================
% 
%  Major output:
%  - Figure 7: AV and its components of the German fund sector over time.
%  - Figure 8: Actual and null model AVs.
%  - Figure IA.2: Illustrative example of Step 1 losses due to cross-fund holdings (motivating example with two funds).
%  - Figure IA.3: Sensitivity analysis for the main model parameters.
%  - Figure IA.4: Joint sensitivity analysis.
%  - Figure IA.8: AV over time by fund type and retail/institutional.
%  - Figure IA.9: Concentration of S and V.
%  - Table IA.4: Persistence of fund-level systemicness and vulnerability.
%
%  =======================================================================================================================================================
% 
%  General disclaimer:
%  This file directory produces replication code for "Connected Funds". 
%  Because we cannot share the underlying data provided by the Bundesbank's Research Data and Service Centre (RDSC) and other subscription data sources, 
%  we have included pseudo data to show how the raw data are formatted.
%  Other researchers can go through a similar approval and subscription process to obtain the underlying data. (2023-04-06)
% 
%  =======================================================================================================================================================

projectPath = 'C:\ConnectedFunds_Codebase\'

% Add functions folders
addpath(strcat(projectPath, 'Code\matlab_functions'));


%%  ================================================================ Preparations ======================================================================


% Load results
load(strcat(projectpath, 'Data\StresstestModel\AV_Application_LongSample.mat'));
dates = datenum(string(umonth),'yyyymm');

% Load fund-month-level data
load(strcat(projectpath,  'Data\IFS\IFS_All_CleanData.mat'))


kill = find(ismember(IFS_All.artmittel, [4 5 6]) | IFS_All.artmittel > 7 | IFS_All.etf == 1);

IFS_All(kill, :) = [];

[~, idx] = ismember(IFS_All.ISIN, ufund_all);

Fund_Artmittel = accumarray(idx, IFS_All.artmittel, [length(ufund_all) 1], @max);
Fund_Spezial   = accumarray(idx, IFS_All.SPEZIAL, [length(ufund_all) 1], @max);

Fund_TNA = NaN(Tmonth, length(ufund_all));

for t = 1:Tmonth
    IFS_All_t = IFS_All(IFS_All.DATUM == umonth(t), :);
    FundsAlive = find(ismember(ufund_all, IFS_All_t.ISIN));
    Fund_TNA(t, FundsAlive) = IFS_All_t.FONDSVERM;
end

% Express TNA in EUR
Fund_TNA = Fund_TNA * 1000;

clear idx* ufund kill FundsAlive IFS_All_t;


%%  ================================================================ Figure 8: Actual and null model AVs. ======================================================================


X = 100*abs([Results_AV5(:,1) Results_Lookthrough_AV5(:,1) Results_AV_H05(:,1)]);

close
plot(dates,[X(:,1) X(:,2:3)]); 
datetick('x','yyyy'); axis tight; grid on; xtickangle(45); axis square;
ylabel('AV (in %)'); xlabel('Year'); ylim([0.75 2.25]);
legend('Actual','Null Model A: Look-through','Null Model B: Direct','location','south');
saveas(gcf, strcat(projectpath, 'Paper\Figures\Fig8_Actual and null model AVs.png'),'png');


%%  ==================================================== Figure 7 (left): AV and its components of the German fund sector over time. ===============================================================


% AV Decomposition by contagion type
close
yyaxis left
h = area(dates,100*abs(Results_AV5(:,2:end))); 
xlabel('Year'); 
datetick('x','yyyy'); axis tight; grid on; xtickangle(45); axis square;
ylabel('AV (in %)'); xlabel('Year'); 
ylim([0 2.5]);
yyaxis right
plot(dates,100*Results_AV_CrossHoldings5,'LineWidth',2);
ylim([0 50]);
ylabel('Contribution: cross-fund holdings (in %)');
h(1).FaceColor = 'blue';
h(2).FaceColor = 'green';
h(3).FaceColor = 'yellow';
h(4).FaceColor = 'cyan';
legend({'Loss^{Sales:Direct}','Loss^{Sales:CrossFund}','Loss^{CrossFund}_1','Loss^{CrossFund}_3',strcat("AV contribution:", string(newline), "cross-fund holdings")},'location','EastOutside'); %,'orientation','horizontal'); 
saveas(gcf, strcat(projectpath, 'Paper\Figures\Fig7L_AV and its components of the German fund sector over time.png'),'png');


%%  ==================================================== Figure IA.8: AV over time by fund type and retail/institutional. ===============================================================


% AV Decomposition by fund type
close
yyaxis left
h = area(dates, 100 * [nansum(abs(Results_FundSystemicness5(:, Fund_Artmittel==1 & Fund_Spezial == 0))')' ...
                       nansum(abs(Results_FundSystemicness5(:, Fund_Artmittel==1 & Fund_Spezial == 1))')' ...
                       nansum(abs(Results_FundSystemicness5(:, Fund_Artmittel==2 & Fund_Spezial == 0))')' ...
                       nansum(abs(Results_FundSystemicness5(:, Fund_Artmittel==2 & Fund_Spezial == 1))')' ...
                       nansum(abs(Results_FundSystemicness5(:, Fund_Artmittel==3 & Fund_Spezial == 0))')' ...
                       nansum(abs(Results_FundSystemicness5(:, Fund_Artmittel==3 & Fund_Spezial == 1))')' ...
                       nansum(abs(Results_FundSystemicness5(:, Fund_Artmittel==7 & Fund_Spezial == 0))')' ...
                       nansum(abs(Results_FundSystemicness5(:, Fund_Artmittel==7 & Fund_Spezial == 1))')']);
h(1).FaceColor = 'blue';
h(1).FaceAlpha = 0.3;
h(2).FaceColor = 'blue';
h(3).FaceColor = 'red';
h(3).FaceAlpha = 0.3;
h(4).FaceColor = 'red';
h(5).FaceColor = 'green';
h(5).FaceAlpha = 0.3;
h(6).FaceColor = 'green';
h(7).FaceColor = 'cyan';
h(7).FaceAlpha = 0.3;
h(8).FaceColor = 'cyan';
datetick('x','yyyy'); axis tight; grid on; xtickangle(45); axis square;
ylabel('AV (in %)'); xlabel('Year'); 
ylim([0 2.5]);
yyaxis right
plot(dates, 100 * Results_AV_CrossHoldings5, 'LineWidth', 2);
ylim([0 50]); 
ylabel('Contribution: cross-fund holdings (in %)');
legend('Equity - Retail', 'Equity - Inst.', 'Bond - Retail', 'Bond - Inst.',  ...
       'Mixed - Retail', 'Mixed - Inst.', 'FoF - Retail', 'FoF - Inst.', strcat("AV contribution:", string(newline), "cross-fund holdings"), 'location','EastOutside');
saveas(gcf, strcat(projectpath, 'Paper\Figures\FigIA8_AV over time by fund type and retail vs institutional.png'),'png');


%%  ==================================================== Figure 7 (right): AV and its components of the German fund sector over time. ===============================================================


% AV Decomposition by fund type and contagion channel
Systemicness_EF =[]; Systemicness_BF =[]; Systemicness_MF =[]; Systemicness_FF =[];

Results_FundSystemicness5           = abs(Results_FundSystemicness5);
Results_FundSystemicness5_Direct    = abs(Results_FundSystemicness5_Direct);
Results_FundSystemicness5_CrossFund = abs(Results_FundSystemicness5_CrossFund);

for t = 1 : Tmonth
    
    Systemicness_EF(t, 1:3) = [ nansum(Results_FundSystemicness5(t,Fund_Artmittel==1)) ...
                                nansum(Results_FundSystemicness5_Direct(t,Fund_Artmittel==1))  ...
                                nansum(Results_FundSystemicness5_CrossFund(t,Fund_Artmittel==1))];


    Systemicness_BF(t, 1:3) = [ nansum(Results_FundSystemicness5(t,Fund_Artmittel==2)) ...
                                nansum(Results_FundSystemicness5_Direct(t,Fund_Artmittel==2))  ...
                                nansum(Results_FundSystemicness5_CrossFund(t,Fund_Artmittel==2))];   


    Systemicness_MF(t, 1:3) = [ nansum(Results_FundSystemicness5(t,Fund_Artmittel==3)) ...
                                nansum(Results_FundSystemicness5_Direct(t,Fund_Artmittel==3))  ...
                                nansum(Results_FundSystemicness5_CrossFund(t,Fund_Artmittel==3))]; 


    Systemicness_FF(t, 1:3) = [ nansum(Results_FundSystemicness5(t,Fund_Artmittel==7)) ...
                                nansum(Results_FundSystemicness5_Direct(t,Fund_Artmittel==7))  ...
                                nansum(Results_FundSystemicness5_CrossFund(t,Fund_Artmittel==7))];  


    Systemicness_Retail(t, 1:3) = [ nansum(Results_FundSystemicness5(t,Fund_Spezial==0)) ...
                                nansum(Results_FundSystemicness5_Direct(t,Fund_Spezial==0))  ...
                                nansum(Results_FundSystemicness5_CrossFund(t,Fund_Spezial==0))];  

    Systemicness_Institutional(t, 1:3) = [ nansum(Results_FundSystemicness5(t,Fund_Spezial==1)) ...
                                nansum(Results_FundSystemicness5_Direct(t,Fund_Spezial==1))  ...
                                nansum(Results_FundSystemicness5_CrossFund(t,Fund_Spezial==1))];  

end

% AV Decomposition by fund type and contagion channel
close all
h = area(dates, [Systemicness_EF(:, 2), Systemicness_EF(:, 3), Systemicness_BF(:, 2), Systemicness_BF(:, 3), ...
                 Systemicness_MF(:, 2), Systemicness_MF(:, 3), Systemicness_FF(:, 2), Systemicness_FF(:, 3)] .* 100)
h(1).FaceColor = 'blue';
h(1).FaceAlpha = 0.3;
h(2).FaceColor = 'blue';
h(3).FaceColor = 'red';
h(3).FaceAlpha = 0.3;
h(4).FaceColor = 'red';
h(5).FaceColor = 'green';
h(5).FaceAlpha = 0.3;
h(6).FaceColor = 'green';
h(7).FaceColor = 'cyan';
h(7).FaceAlpha = 0.3;
h(8).FaceColor = 'cyan';
xlabel('Year');
legend('Equity - Sales:Direct', 'Equity - CrossFund', 'Bond - Sales:Direct', 'Bond - CrossFund',  ...
       'Mixed - Sales:Direct', 'Mixed - CrossFund', 'FoF - Sales:Direct', 'FoF - CrossFund', ...
       'Location', 'EastOutside', 'Orientation', 'vertical')
datetick('x','yyyy'); axis tight; grid on; xtickangle(45); axis square;
ylabel('AV (in %)'); xlabel('Year'); 
ylim([0 2.5]); 
saveas(gcf, strcat(projectpath, 'Paper\Figures\Fig7R_AV and its components of the German fund sector over time.png'),'png');


%%  ==================================================== Figure IA.3: Sensitivity analysis for the main model parameters (date: 2019-12). ===============================================================


% Amihud ratio / price impact 
close
yyaxis left
h = area(100*factor,100*abs(ResultsSensi_AV_Amihud5(:,2:end)));
xlabel('Factor (in %)'); 
grid on; axis square;
ylabel('AV (in %)'); title('PriceImpact');
yyaxis right
plot(100*factor,100*ResultsSensi_AV_CrossHoldings_Amihud5,'LineWidth',2);
xline(100,'k--','Baseline')
ylim([0 60]);
ylabel('Contribution: cross-fund holdings (in %)');
h(1).FaceColor = 'blue';
h(2).FaceColor = 'green';
h(3).FaceColor = 'yellow';
h(4).FaceColor = 'cyan';
legend({'Fire sales (direct)','Fire sales (cross-fund)','Loss^{CrossFund}_1','Loss^{CrossFund}_3',strcat("AV contribution:", string(newline), "cross-fund holdings")},'location','EastOutside'); 
saveas(gcf, strcat(projectpath, 'Paper\Figures\FigIA3TR_Sensitivity analysis for the main model parameters.png'),'png');

% Gamma (flow-driven channel)
close
yyaxis left
h = area(100*factor,100*abs(ResultsSensi_AV_Gamma5(:,2:end)));
xlabel('Factor (in %)'); 
grid on; axis square;
ylabel('AV (in %)'); title('Flow-driven: \gamma');
yyaxis right
plot(100*factor,100*ResultsSensi_AV_CrossHoldings_Gamma5,'LineWidth',2);
xline(100,'k--','Baseline')
ylim([0 60]);
ylabel('Contribution: cross-fund holdings (in %)');
h(1).FaceColor = 'blue';
h(2).FaceColor = 'green';
h(3).FaceColor = 'yellow';
h(4).FaceColor = 'cyan';
legend({'Fire sales (direct)','Fire sales (cross-fund)','Loss^{CrossFund}_1','Loss^{CrossFund}_3',strcat("AV contribution:", string(newline), "cross-fund holdings")},'location','EastOutside'); 
saveas(gcf, strcat(projectpath, 'Paper\Figures\FigIA3BL_Sensitivity analysis for the main model parameters.png'),'png');

% Beta and Theta (non-flow-driven channel)
close
yyaxis left
h = area(100*factor,100*abs(ResultsSensi_AV_BetaTheta5(:,2:end)));
xlabel('Factor (in %)'); 
grid on; axis square;
ylabel('AV (in %)'); title('Non-flow-driven: \beta, \theta');
yyaxis right
plot(100*factor,100*ResultsSensi_AV_CrossHoldings_BetaTheta5,'LineWidth',2);
xline(100,'k--','Baseline')
ylim([0 60]);
ylabel('Contribution: cross-fund holdings (in %)');
h(1).FaceColor = 'blue';
h(2).FaceColor = 'green';
h(3).FaceColor = 'yellow';
h(4).FaceColor = 'cyan';
legend({'Fire sales (direct)','Fire sales (cross-fund)','Loss^{CrossFund}_1','Loss^{CrossFund}_3',strcat("AV contribution:", string(newline), "cross-fund holdings")},'location','EastOutside'); 
saveas(gcf, strcat(projectpath, 'Paper\Figures\FigIA3BR_Sensitivity analysis for the main model parameters.png'),'png');

% Initial shock
close
yyaxis left
h = area(100*factor,100*abs(ResultsSensi_AV_InitialShock5(:,2:end)));
xlabel('Factor (in %)'); 
grid on; axis square;
ylabel('AV (in %)'); title('Initial shock');
yyaxis right
plot(100*factor,100*ResultsSensi_AV_CrossHoldings_InitialShock5,'LineWidth',2);
xline(100,'k--','Baseline')
ylim([0 60]);
ylabel('Contribution: cross-fund holdings (in %)');
h(1).FaceColor = 'blue';
h(2).FaceColor = 'green';
h(3).FaceColor = 'yellow';
h(4).FaceColor = 'cyan';
legend({'Fire sales (direct)','Fire sales (cross-fund)','Loss^{CrossFund}_1','Loss^{CrossFund}_3',strcat("AV contribution:", string(newline), "cross-fund holdings")},'location','EastOutside'); 
saveas(gcf, strcat(projectpath, 'Paper\Figures\FigIA3TL_Sensitivity analysis for the main model parameters.png'),'png');


%%  ==================================================================== Figure IA.4: Joint sensitivity analysis (date: 2019-12). ===============================================================================


% All parameters jointly
close
yyaxis left
h = area(100*factor,100*abs(ResultsSensi_AV_All5(:,2:end)));
xlabel('Factor (in %)'); 
grid on; axis square;
ylabel('AV (in %)'); title('All model parameters');
yyaxis right
plot(100*factor,100*ResultsSensi_AV_CrossHoldings_All5,'LineWidth',2);
xline(100,'k--','Baseline')
ylim([0 60]);
ylabel('Contribution: cross-fund holdings (in %)');
h(1).FaceColor = 'blue';
h(2).FaceColor = 'green';
h(3).FaceColor = 'yellow';
h(4).FaceColor = 'cyan';
legend({'Fire sales (direct)','Fire sales (cross-fund)','Loss^{CrossFund}_1','Loss^{CrossFund}_3',strcat("AV contribution:", string(newline), "cross-fund holdings")},'location','EastOutside'); 
saveas(gcf, strcat(projectpath, 'Paper\Figures\FigIA4_Joint sensitivity analysis.png'),'png');


%%  ==================================================================== A closer look at fund-level results ===============================================================================


Nfunds = size(ufund_all, 1)

nancorr(abs(Results_FundReturn5(:)), abs(Results_FundSystemicness5(:)))
nancorr(abs(Results_FundLossCross5(:)), abs(Results_FundSystemicness5_CrossFund(:)))

Fund_Decile_Vulnerability5           = NaN(Tmonth,Nfunds);
Fund_Decile_Systemicness5            = NaN(Tmonth,Nfunds);
Fund_Decile_Systemicness_crossfund5  = NaN(Tmonth,Nfunds);
Fund_Decile_Vulnerability_crossfund5 = NaN(Tmonth,Nfunds);
Fund_Decile_TNA                      = NaN(Tmonth,Nfunds);
Fund_Decile_InitialShock             = NaN(Tmonth,Nfunds);

Decile_Vulnerability5           = NaN(Tmonth,10);
Decile_Systemicness5            = NaN(Tmonth,10);
Decile_Systemicness_crossfund5  = NaN(Tmonth,10);
Decile_Vulnerability_crossfund5 = NaN(Tmonth,10);
Decile_TNA                      = NaN(Tmonth,10);
Decile_InitialShock             = NaN(Tmonth,10);

C_VS  = NaN(Tmonth, 2);

for t = 1:Tmonth
    ii = find(isnan(Results_FundReturn5(t,:))==0); 
    
    v5  = 100*abs(Results_FundReturn5(t,ii))';            
    s5  = 100*abs(Results_FundSystemicness5(t,ii))';     

    InitialShock = 100 * abs(Results_FundInitialShock5(t, ii))';
    
    s_crossfund_5  = 100*abs(Results_FundSystemicness5_CrossFund(t,ii))';       
    v_crossfund_5  = 100*abs(Results_FundLossCross5(t,ii))';
    
    tna = Fund_TNA(t, ii)'; 

    C_VS(t,:) = [corr(v5, s5), corr(v_crossfund_5, s_crossfund_5)];
    
    % Get deciles of systemicness
    rank   = getRank(s5);
    rank   = rank./max(rank);
    decile = ceil(10*rank);
    Fund_Decile_Systemicness5(t,ii)  = decile;
    
    for i = 1:10 
        Decile_Systemicness5(t,i) = mean(s5(decile==i)); 
    end
      
    % Get deciles of systemicness_crossfund
    rank   = getRank(s_crossfund_5);
    rank   = rank./max(rank);
    decile = ceil(10*rank);
    Fund_Decile_Systemicness_crossfund5(t,ii)  = decile;
    
    for i = 1:10 
        Decile_Systemicness_crossfund5(t,i) = mean(s5(decile==i)); 
    end

    % Get deciles of vulnerability_crossfund
    rank   = getRank(v_crossfund_5);
    rank   = rank./max(rank);
    decile = ceil(10*rank);
    Fund_Decile_Vulnerability_crossfund5(t,ii)  = decile;
    
    for i = 1:10 
        Decile_Vulnerability_crossfund5(t,i) = mean(s5(decile==i)); 
    end

    % Get deciles of fund vulnerability
    rank   = getRank(v5);
    rank   = rank./max(rank);
    decile = ceil(10*rank);
    Fund_Decile_Vulnerability5(t,ii)  = decile;
    
    for i = 1:10 
        Decile_Vulnerability5(t,i) = mean(v5(decile==i)); 
    end
    
    % Get deciles of fund TNA
    rank   = getRank(tna);
    rank   = rank./max(rank);
    decile = ceil(10*rank);
    Fund_Decile_TNA(t,ii) = decile;
   
    for i = 1:10 
        Decile_TNA(t,i) = mean(tna(decile==i)); 
    end

    % Get deciles of initial shock
    rank   = getRank(InitialShock);
    rank   = rank./max(rank);
    decile = ceil(10*rank);
    Fund_Decile_InitialShock(t,ii)  = decile;
    
    for i = 1:10 
        Decile_InitialShock(t,i) = mean(InitialShock(decile==i)); 
    end
    
    clear v5 v1 v_crossfund_5 s5 s1 s_crossfund_5 tna InitialShock;
end


%%  ========================================================= Table IA.4: Persistence of fund-level systemicness and vulnerability ==============================================================


% Transition matrix: persistence --> damage drivers

% Short-term persistence: t + 1
C = crosstab(vect(Fund_Decile_Systemicness5(1:end-1, :)), vect(Fund_Decile_Systemicness5(2:end, :)));
C = 100 * (C ./ repmat(sum(C')', 1, 10)) % value in percent
writematrix(C, strcat(projectpath, 'Paper\Tables\TabIA4T_Persistence of fund-level systemicness and vulnerability.xlsx'));

% medium-term persistence: t + 12
C = crosstab(vect(Fund_Decile_Systemicness5(1:12:end-12, :)), vect(Fund_Decile_Systemicness5(13:12:end, :)));
C = 100 * (C./repmat(sum(C')',1,10)) % value in percent
writematrix(C, strcat(projectpath, 'Paper\Tables\TabIA4T_Persistence of fund-level systemicness and vulnerability.xlsx'), 'Range', 'K1:T10');

% Transition matrix: persistence --> damage receivers

% Short-term persistence: t + 1
C = crosstab(vect(Fund_Decile_Vulnerability5(1:end-1, :)), vect(Fund_Decile_Vulnerability5(2:end, :)));
C = 100 * (C ./ repmat(sum(C')', 1, 10)) % value in percent
writematrix(C, strcat(projectpath, 'Paper\Tables\TabIA4B_Persistence of fund-level systemicness and vulnerability.xlsx'));

% medium-term persistence: t + 12
C = crosstab(vect(Fund_Decile_Vulnerability5(1:12:end-12, :)), vect(Fund_Decile_Vulnerability5(13:12:end, :)));
C = 100 * (C./repmat(sum(C')',1,10)) % value in percent
writematrix(C, strcat(projectpath, 'Paper\Tables\TabIA4B_Persistence of fund-level systemicness and vulnerability.xlsx'), 'Range', 'K1:T10');


%%  ============================================================================== Figure IA.9: Concentration of S and V. ===================================================================================


Vulnerability_FundLevel= 100 * abs(Results_FundTotalLoss5);
isVulnerability10thDecile = zeros(size(Fund_Decile_Vulnerability5, 1), size(Fund_Decile_Vulnerability5, 2));
isVulnerability9thDecile = zeros(size(Fund_Decile_Vulnerability5, 1), size(Fund_Decile_Vulnerability5, 2));
isVulnerability8thDecile = zeros(size(Fund_Decile_Vulnerability5, 1), size(Fund_Decile_Vulnerability5, 2));
isVulnerability7thDecile = zeros(size(Fund_Decile_Vulnerability5, 1), size(Fund_Decile_Vulnerability5, 2));
isVulnerability6thDecile = zeros(size(Fund_Decile_Vulnerability5, 1), size(Fund_Decile_Vulnerability5, 2));
isVulnerability5thDecile = zeros(size(Fund_Decile_Vulnerability5, 1), size(Fund_Decile_Vulnerability5, 2));
isVulnerability4thDecile = zeros(size(Fund_Decile_Vulnerability5, 1), size(Fund_Decile_Vulnerability5, 2));
isVulnerability3rdDecile = zeros(size(Fund_Decile_Vulnerability5, 1), size(Fund_Decile_Vulnerability5, 2));
isVulnerability2ndDecile = zeros(size(Fund_Decile_Vulnerability5, 1), size(Fund_Decile_Vulnerability5, 2));
isVulnerability1stDecile = zeros(size(Fund_Decile_Vulnerability5, 1), size(Fund_Decile_Vulnerability5, 2));

isVulnerability10thDecile(Fund_Decile_Vulnerability5 == 10)  = 1;
isVulnerability9thDecile(Fund_Decile_Vulnerability5 == 9)    = 1;
isVulnerability8thDecile(Fund_Decile_Vulnerability5 == 8)    = 1;
isVulnerability7thDecile(Fund_Decile_Vulnerability5 == 7)    = 1;
isVulnerability6thDecile(Fund_Decile_Vulnerability5 == 6)    = 1;
isVulnerability5thDecile(Fund_Decile_Vulnerability5 == 5)    = 1;
isVulnerability4thDecile(Fund_Decile_Vulnerability5 == 4)    = 1;
isVulnerability3rdDecile(Fund_Decile_Vulnerability5 == 3)    = 1;
isVulnerability2ndDecile(Fund_Decile_Vulnerability5 == 2)    = 1;
isVulnerability1stDecile(Fund_Decile_Vulnerability5 == 1)    = 1;

AggVulnerability10thDecile = nanmean(Vulnerability_FundLevel .* isVulnerability10thDecile, 2);
AggVulnerability9thDecile = nanmean(Vulnerability_FundLevel .* isVulnerability9thDecile, 2);
AggVulnerability8thDecile = nanmean(Vulnerability_FundLevel .* isVulnerability8thDecile, 2);
AggVulnerability7thDecile = nanmean(Vulnerability_FundLevel .* isVulnerability7thDecile, 2);
AggVulnerability6thDecile = nanmean(Vulnerability_FundLevel .* isVulnerability6thDecile, 2);
AggVulnerability5thDecile = nanmean(Vulnerability_FundLevel .* isVulnerability5thDecile, 2);
AggVulnerability4thDecile = nanmean(Vulnerability_FundLevel .* isVulnerability4thDecile, 2);
AggVulnerability3rdDecile = nanmean(Vulnerability_FundLevel .* isVulnerability3rdDecile, 2);
AggVulnerability2ndDecile = nanmean(Vulnerability_FundLevel .* isVulnerability2ndDecile, 2);
AggVulnerability1stDecile = nanmean(Vulnerability_FundLevel .* isVulnerability1stDecile, 2);

AggTNAVulnerability10thDecile = nansum(Fund_TNA .* isVulnerability10thDecile, 2);
AggTNAVulnerability9thDecile = nansum(Fund_TNA .* isVulnerability9thDecile, 2);
AggTNAVulnerability8thDecile = nansum(Fund_TNA .* isVulnerability8thDecile, 2);
AggTNAVulnerability7thDecile = nansum(Fund_TNA .* isVulnerability7thDecile, 2);
AggTNAVulnerability6thDecile = nansum(Fund_TNA .* isVulnerability6thDecile, 2);
AggTNAVulnerability5thDecile = nansum(Fund_TNA .* isVulnerability5thDecile, 2);
AggTNAVulnerability4thDecile = nansum(Fund_TNA .* isVulnerability4thDecile, 2);
AggTNAVulnerability3rdDecile = nansum(Fund_TNA .* isVulnerability3rdDecile, 2);
AggTNAVulnerability2ndDecile = nansum(Fund_TNA .* isVulnerability2ndDecile, 2);
AggTNAVulnerability1stDecile = nansum(Fund_TNA .* isVulnerability1stDecile, 2);

Systemicness_FundLevel= 100 * abs(Results_FundSystemicness5);
isSystemicness10thDecile = zeros(size(Fund_Decile_Systemicness5, 1), size(Fund_Decile_Systemicness5, 2));
isSystemicness9thDecile = zeros(size(Fund_Decile_Systemicness5, 1), size(Fund_Decile_Systemicness5, 2));
isSystemicness8thDecile = zeros(size(Fund_Decile_Systemicness5, 1), size(Fund_Decile_Systemicness5, 2));
isSystemicness7thDecile = zeros(size(Fund_Decile_Systemicness5, 1), size(Fund_Decile_Systemicness5, 2));
isSystemicness6thDecile = zeros(size(Fund_Decile_Systemicness5, 1), size(Fund_Decile_Systemicness5, 2));
isSystemicness5thDecile = zeros(size(Fund_Decile_Systemicness5, 1), size(Fund_Decile_Systemicness5, 2));
isSystemicness4thDecile = zeros(size(Fund_Decile_Systemicness5, 1), size(Fund_Decile_Systemicness5, 2));
isSystemicness3rdDecile = zeros(size(Fund_Decile_Systemicness5, 1), size(Fund_Decile_Systemicness5, 2));
isSystemicness2ndDecile = zeros(size(Fund_Decile_Systemicness5, 1), size(Fund_Decile_Systemicness5, 2));
isSystemicness1stDecile = zeros(size(Fund_Decile_Systemicness5, 1), size(Fund_Decile_Systemicness5, 2));

isSystemicness10thDecile(Fund_Decile_Systemicness5 == 10)  = 1;
isSystemicness9thDecile(Fund_Decile_Systemicness5 == 9)    = 1;
isSystemicness8thDecile(Fund_Decile_Systemicness5 == 8)    = 1;
isSystemicness7thDecile(Fund_Decile_Systemicness5 == 7)    = 1;
isSystemicness6thDecile(Fund_Decile_Systemicness5 == 6)    = 1;
isSystemicness5thDecile(Fund_Decile_Systemicness5 == 5)    = 1;
isSystemicness4thDecile(Fund_Decile_Systemicness5 == 4)    = 1;
isSystemicness3rdDecile(Fund_Decile_Systemicness5 == 3)    = 1;
isSystemicness2ndDecile(Fund_Decile_Systemicness5 == 2)    = 1;
isSystemicness1stDecile(Fund_Decile_Systemicness5 == 1)    = 1;

AggSystemicness10thDecile = nansum(Systemicness_FundLevel .* isSystemicness10thDecile, 2);
AggSystemicness9thDecile = nansum(Systemicness_FundLevel .* isSystemicness9thDecile, 2);
AggSystemicness8thDecile = nansum(Systemicness_FundLevel .* isSystemicness8thDecile, 2);
AggSystemicness7thDecile = nansum(Systemicness_FundLevel .* isSystemicness7thDecile, 2);
AggSystemicness6thDecile = nansum(Systemicness_FundLevel .* isSystemicness6thDecile, 2);
AggSystemicness5thDecile = nansum(Systemicness_FundLevel .* isSystemicness5thDecile, 2);
AggSystemicness4thDecile = nansum(Systemicness_FundLevel .* isSystemicness4thDecile, 2);
AggSystemicness3rdDecile = nansum(Systemicness_FundLevel .* isSystemicness3rdDecile, 2);
AggSystemicness2ndDecile = nansum(Systemicness_FundLevel .* isSystemicness2ndDecile, 2);
AggSystemicness1stDecile = nansum(Systemicness_FundLevel .* isSystemicness1stDecile, 2);

AggTNASystemicness10thDecile = nansum(Fund_TNA .* isSystemicness10thDecile, 2);
AggTNASystemicness9thDecile = nansum(Fund_TNA .* isSystemicness9thDecile, 2);
AggTNASystemicness8thDecile = nansum(Fund_TNA .* isSystemicness8thDecile, 2);
AggTNASystemicness7thDecile = nansum(Fund_TNA .* isSystemicness7thDecile, 2);
AggTNASystemicness6thDecile = nansum(Fund_TNA .* isSystemicness6thDecile, 2);
AggTNASystemicness5thDecile = nansum(Fund_TNA .* isSystemicness5thDecile, 2);
AggTNASystemicness4thDecile = nansum(Fund_TNA .* isSystemicness4thDecile, 2);
AggTNASystemicness3rdDecile = nansum(Fund_TNA .* isSystemicness3rdDecile, 2);
AggTNASystemicness2ndDecile = nansum(Fund_TNA .* isSystemicness2ndDecile, 2);
AggTNASystemicness1stDecile = nansum(Fund_TNA .* isSystemicness1stDecile, 2);


%% Systemicness deciles by total net assets managed
SystemicnessDeciles = [[AggTNASystemicness1stDecile, AggTNASystemicness2ndDecile, AggTNASystemicness3rdDecile, AggTNASystemicness4thDecile, ...
    AggTNASystemicness5thDecile, AggTNASystemicness6thDecile, AggTNASystemicness7thDecile, AggTNASystemicness8thDecile, ...
    AggTNASystemicness9thDecile, AggTNASystemicness10thDecile] ./ nansum(Fund_TNA, 2) * 100, ...
    [AggSystemicness1stDecile, AggSystemicness2ndDecile, AggSystemicness3rdDecile, AggSystemicness4thDecile, ...
    AggSystemicness5thDecile, AggSystemicness6thDecile, AggSystemicness7thDecile, AggSystemicness8thDecile, ...
    AggSystemicness9thDecile, AggSystemicness10thDecile] ./ nansum(Systemicness_FundLevel, 2) * 100];

plot_colors = [{'green'}, {'black'}, {'black'}, {'black'}, {'black'}, {'black'}, {'black'}, {'black'}, {'black'}, {'red'}];

figure
hold on

for i = size(plot_colors, 2) : -1 : 1
    plot(mean(SystemicnessDeciles(:, i)), mean(SystemicnessDeciles(:, i + 10)), 'o', 'MarkerFaceColor', char(plot_colors(i)), ...
        'MarkerEdgeColor', char(plot_colors(i)), 'LineWidth',   1);
end

ylabel('Mean Systemicness (% of Aggregate Vulnerability)'); xlabel('Size (% of Aggregate Fund Sector Net Assets)');
axis square; axis square; grid on; axis([0 70 0 70]); 
legend({'Q10 (High systemicness)', 'Q9', 'Q8', 'Q7', 'Q6', 'Q5', 'Q4', 'Q3', 'Q2', 'Q1 (Low systemicness)'}, 'Location', 'EastOutside')
saveas(gcf, strcat(projectpath, 'Paper\Figures\FigIA9T_Concentration of S and V.png'),'png');
hold off


%% Vulnerability deciles by total net assets managed
VulnerabilityDeciles = [[AggTNAVulnerability1stDecile, AggTNAVulnerability2ndDecile, AggTNAVulnerability3rdDecile, AggTNAVulnerability4thDecile, ...
    AggTNAVulnerability5thDecile, AggTNAVulnerability6thDecile, AggTNAVulnerability7thDecile, AggTNAVulnerability8thDecile, ...
    AggTNAVulnerability9thDecile, AggTNAVulnerability10thDecile] ./ nansum(Fund_TNA, 2) * 100, ...
    [AggVulnerability1stDecile, AggVulnerability2ndDecile, AggVulnerability3rdDecile, AggVulnerability4thDecile, ...
    AggVulnerability5thDecile, AggVulnerability6thDecile, AggVulnerability7thDecile, AggVulnerability8thDecile, ...
    AggVulnerability9thDecile, AggVulnerability10thDecile] * 100];

plot_colors = [{'green'}, {'black'}, {'black'}, {'black'}, {'black'}, {'black'}, {'black'}, {'black'}, {'black'}, {'red'}];

figure
hold on

for i = size(plot_colors, 2) : -1 : 1
    plot(mean(VulnerabilityDeciles(:, i)), mean(VulnerabilityDeciles(:, i + 10)), 'o', 'MarkerFaceColor', char(plot_colors(i)), ...
        'MarkerEdgeColor', char(plot_colors(i)), 'LineWidth',   1);
end

ylabel('Mean Vulnerability (% of fund TNA)'); xlabel('Size (% of aggregate fund sector net assets)');
axis square; axis square; grid on; axis([0 50 0 50]); 
legend({'Q10 (High vulnerability)', 'Q9', 'Q8', 'Q7', 'Q6', 'Q5', 'Q4', 'Q3', 'Q2', 'Q1 (Low vulnerability)'}, 'Location', 'EastOutside')
saveas(gcf, strcat(projectpath, 'Paper\Figures\FigIA9B_Concentration of S and V.png'),'png');
hold off


%%  ========== Figure IA.2: Illustrative example of Step 1 losses due to cross-fund holdings (motivating example with two funds). ===========


clear all
close all

projectpath = 'C:\ConnectedFunds_Codebase\';

r2 = -0.15;

values       = (-0.3:0.01:0);
fund_weights = [0.1 0.2 0.3]; 

Results_RE0_Fund1 = zeros(length(values),1);
Results_RE1_Fund1 = zeros(length(values),1);

Results_RE0_Fund2 = zeros(length(values),length(fund_weights));
Results_RE1_Fund2 = zeros(length(values),length(fund_weights));

for w = 1 : length(fund_weights)
    
    weight    = fund_weights(w);
    
    a_FUND    = [0 0; weight 0];
    a_ASSET   = [1 0; 0 1-weight];

    wInv      = inv(eye(2) - a_FUND);

    for j = 1 : length(values)

        r1      = values(j);
        RE0_1   = r1;
        RE0_2   = a_ASSET(2,2)*r2;
        RE0     = [RE0_1; RE0_2];
        RE1     = wInv*RE0;

        Results_RE0_Fund1(j) = RE0(1);
        Results_RE1_Fund1(j) = RE1(1);
        
        Results_RE0_Fund2(j,w) = RE0(2);
        Results_RE1_Fund2(j,w) = RE1(2);

    end
end

close
plot(100 *  values, 100 * Results_RE0_Fund1, 'r', 100 * values, 100 * Results_RE0_Fund2(:, 2), 'g--', 100 * values, 100 * Results_RE1_Fund2(:, 2), 'g-', 100 * values, -15 * ones(length(values), 1), 'k-')
xline(100 * r2, 'k:', 'Shock Asset B'); 
legend('Fund 1: $R^E_{0,1}$ = $R^E_{1,1}$', 'Fund 2: $R^E_{0,2}$ $(a^{FUND}_{2,1} = 0.2)$', 'Fund 2: $R^E_{1,2}$ $(a^{FUND}_{2,1} = 0.2)$', 'Fund 2: $R^E_{0,2} = R^E_{1,2}$ $(a^{FUND}_{2,1} = 0)$', 'interpreter', 'latex', 'location', 'SouthEast');
xlabel('Shock Asset A (in percent)'); ylabel('Fund Return (in percent)'); grid on;
saveas(gcf, strcat(projectpath, 'Paper\Figures\FigIA2_Illustrative example of Step 1 losses due to cross-fund holdings.png'), 'png');